<?php

namespace app\models\user;

use app\models\product\Product;
use app\models\product\ProductSku;
use Yii;

/**
 * This is the model class for table "user_cart".
 *
 * @property int $id
 * @property int $user_id
 * @property int $product_id product.id 不一定是product,有可能是对应的sku
 * @property int $product_sku_id product_sku.id 不一定是product,有可能是对应的sku
 * @property int $quantity 数量
 * @property int $selected 在购物车中是否选中, 1选中, 0未选中
 * @property string $selected_sku_value sku 值 列表 json {id}
 * @property string $selected_sku_text sku 名称 列表 json{text}
 * @property string $create_time
 * @property string $update_time
 * @property float $price 添加时的价格
 * @property float $score_cost 运营费用
 */
class UserCart extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_cart';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'product_id', 'product_sku_id', 'quantity', 'selected'], 'integer'],
            [['selected_sku_value', 'selected_sku_text'], 'safe'],
            [['create_time', 'update_time'], 'safe'],
            [['price'], 'number'],

            [['score_cost'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'product_id' => 'Product ID',
            'product_sku_id' => 'Product Sku ID',
            'quantity' => 'Quantity',
            'selected' => 'Selected',
            'selected_sku_value' => 'Selected Sku Value',
            'selected_sku_text' => 'Selected Sku Text',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'price' => 'Price',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public function getProduct()
    {
        return $this->hasOne(Product::class, ['id' => 'product_id']);
    }

    public function getSku()
    {
        return $this->hasOne(ProductSku::class, ['id' => 'product_sku_id']);
    }
}
